import React, { useState } from 'react';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { SafeAreaView, StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';
import { useAsyncEffect, useReactive } from 'ahooks';
import LocationClass from '../../../utils/LocationClass.ts';
import to from '../../../utils/to.ts';
import { Button, Text, useToast, View } from 'native-base';
import { CommonStyle } from '../../../common/commonStyle.ts';
import Tools from '../../../utils/Tools.ts';
import Field from '../../../component/Field.tsx';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import UserRequest from '../../../request/userRequest.ts';
import { ShowConfirmDialog } from '../../../component/ConfirmDialog.tsx';
import Picker from '../../../component/Picker.tsx';
import CascadingPicker, { TreeNode } from '../../../component/PickerCascader.tsx';

interface IBindAddressProps {
  navigation: NavigationProp<any, 'bindAddress'>;
  route: RouteProp<any, 'bindAddress'>;
}
interface IState {
  communityList: { text: string; value: number }[]; // 小区列表
  cascader: TreeNode[]; // 选中的楼栋层数据
  cascaderData: TreeNode[]; // 楼栋层数据
  selectedBuildIds: number[]; // 选中的楼栋层ids
  addressDetails?: IGetAddressDetailsRes; // 地址详情
  pickerCommunityShow: boolean;
  pickerBuildShow: boolean;
  params: any; // 呼叫器地址提交保存参数
}

const BindAddress: React.FC<IBindAddressProps> = ({ navigation, route }) => {
  const [active, setActive] = useState<number>(1);
  const [position, setPosition] = useState<{ lat: number; lng: number } | undefined>(undefined);
  const [selectPoint, setSelectPoint] = useState<{ lat: number; lng: number; address: any } | undefined>(undefined);
  const formModel = useReactive({ houseNumber: '', linkName: '', phone: '' });
  const state = useReactive<IState>({ communityList: [], pickerCommunityShow: false, pickerBuildShow: false, cascader: [], cascaderData: [], selectedBuildIds: [], addressDetails: undefined, params: {} });
  const toast = useToast();

  useAsyncEffect(async () => {
    if (route.params) {
      const { houseNumber, phone, linkName, id, beeperId, relationBeeperId } = route.params;
      formModel.phone = phone;
      formModel.linkName = linkName;
      formModel.houseNumber = houseNumber;
      if (relationBeeperId || beeperId) {
        setActive(2);
        fetchAddressDetails(id);
        fetchResidentialAddressList();
      } else {
        setActive(1);
      }
    }
  }, []);

  useAsyncEffect(async () => {
    if (route.params?.message) {
      const message: any = JSON.parse(route.params.message);
      state.params = { ...state.params, address: message.address.address, provinceName: message.address.province, cityName: message.address.city, areaName: message.address.district, streetName: message.address.street, longitude: message.lng, latitude: message.lat };
      setSelectPoint(message);
      setPosition({ lat: message.lat, lng: message.lng });
      if (route.params.relationBeeperId || route.params.beeperId) {
        ['villageId', 'villageName', 'buildHouseNumberNames', 'buildId', 'unitId', 'floorId', 'houseNumberId', 'houseNumber', 'buildName', 'unitName', 'floorName'].forEach((item) => {
          delete state.params[item];
        });
        state.selectedBuildIds = [];
        state.cascader = [];
        state.cascaderData = [];
        fetchResidentialAddressList();
      }
    } else {
      await getPosition();
    }
  }, [route.params]);

  /**
   * 获取定位
   */
  const getPosition = async () => {
    const [err, res] = await to(LocationClass.getLocation());
    if (err) return;
    setPosition(Tools.gpsCoordinateToBaiduCoordinate(res.coords.longitude, res.coords.latitude));
  };

  /**
   * 根据id获取地址详情
   * @param id
   */
  const fetchAddressDetails = (id: number) => {
    UserRequest.GetAddressDetails({ id }).then((res) => {
      const { villageId, villageName, linkName, phone, buildId, unitId, floorId, houseNumberId, houseNumber, buildName, unitName, floorName, relationBeeperType, relationBeeperId, harvestAddressId, beeperId } = res.data;
      state.addressDetails = res.data;
      let ids: number[] = [];
      let names: string = '';
      if (buildId) {
        ids.push(buildId);
        names += buildName;
      }
      if (unitId) {
        ids.push(unitId);
        names += ` ${unitName}`;
      }
      if (floorId) {
        ids.push(floorId);
        names += ` ${floorName}`;
      }
      if (houseNumberId) {
        ids.push(houseNumberId);
        names += ` ${houseNumber}`;
      }
      state.selectedBuildIds = ids;
      state.params = { ...state.params, beeperId, relationBeeperType, relationBeeperId, harvestAddressId, villageId, villageName, linkName, phone, buildId, unitId, floorId, houseNumberId, houseNumber, buildName, unitName, floorName, buildHouseNumberNames: names };
      fetchBuildingTree(villageId);
    });
  };

  /**
   * 获得小区地址列表
   */
  const fetchResidentialAddressList = () => {
    const message: any = JSON.parse(route.params!.message);
    const params = { provinceName: message.address.province, cityName: message.address.city, areaName: message.address.district };
    UserRequest.ResidentialAddressList(params).then((res) => {
      state.communityList = res.data.map((item) => {
        return {
          text: item.name,
          value: item.id,
        };
      });
    });
  };

  /**
   * 获取该小区楼栋层
   * @param villageId
   */
  const fetchBuildingTree = (villageId: number) => {
    UserRequest.BuildingTree({ villageId }).then((res) => {
      state.cascaderData = res.data;
    });
  };

  /**
   * 非呼叫器地址保存地址
   */
  const handleNoBeeperIdSaveAddress = () => {
    if (!formModel.houseNumber) {
      toast.show({ description: '请输入门牌号' });
      return;
    }
    if (!formModel.linkName) {
      toast.show({ description: '请输入联系人' });
      return;
    }
    if (!formModel.phone) {
      toast.show({ description: '请输入联系号码' });
      return;
    }
    const params: any = { ...formModel };

    if (route.params) {
      const { message, variantIds, relationBeeperId, id } = route.params;
      if (relationBeeperId) params.relationBeeperId = relationBeeperId;
      if (id) params.harvestAddressId = id;
      if (variantIds) params.variantIds = variantIds;
      if (message) {
        params.address = JSON.parse(message).address.address;
        params.provinceName = JSON.parse(message).address.province;
        params.cityName = JSON.parse(message).address.city;
        params.areaName = JSON.parse(message).address.district;
        params.areaName = JSON.parse(message).address.district;
        params.streetName = JSON.parse(message).address.streetName;
        params.latitude = Tools.baiduCoordinateToTencentCoordinate(JSON.parse(message).lng, JSON.parse(message).lat).lat;
        params.longitude = Tools.baiduCoordinateToTencentCoordinate(JSON.parse(message).lng, JSON.parse(message).lat).lng;
      }
    }
    if (!params.latitude || !params.longitude) {
      toast.show({ description: '请选择收货地址' });
      return;
    }
    Loading.show('保存中...');
    if (params.harvestAddressId) {
      UserRequest.EditShippingAddress(params)
        .then((res) => {
          afterSuccessfulSav(res, params);
        })
        .catch(() => Loading.hide());
    } else {
      UserRequest.SaveShippingAddress(params)
        .then((res) => {
          afterSuccessfulSav(res, params);
        })
        .catch(() => Loading.hide());
    }
  };

  function afterSuccessfulSav(res: { data: number }, params: any) {
    Loading.hide();
    if (res.data === 0) {
      ShowConfirmDialog({ title: '提示', message: '您的地址超出商家配送范围了', confirmText: '仍然保存', cancelText: '调整地址' }).then(() => {
        params.keepUp = 1;
        UserRequest.SaveShippingAddress(params).then((res) => {
          toast.show({ description: '保存成功', duration: 1000 });
        });
      });
    } else {
      toast.show({ description: '保存成功', duration: 1000 });
      // 从提交订单页面来的那么就需要返回数据回去
      if (route.params?.variantIds) {
      } else {
        navigation.navigate('receivingAddress', { refresh: true });
      }
    }
  }

  /**
   * 删除地址
   */
  const handleDeleteAddress = () => {
    ShowConfirmDialog({ title: '提示', message: '地址删除后无法恢复是否删除地址', confirmText: '确定删除', cancelText: '取消' }).then(() => {
      Loading.show('删除中...');
      UserRequest.DeleteShippingAddress({ id: route.params?.id, state: -1 })
        .then(() => {
          Loading.hide();
          toast.show({ description: '删除成功', duration: 1000 });
          if (route.params?.variantIds) {
          }
          navigation.navigate('receivingAddress', { refresh: true });
        })
        .catch(() => Loading.hide());
    });
  };

  /**
   * 选择器确认
   * @param result
   */
  const handlePickerConfirm = (result: { names: string; values: Array<string | number> }) => {
    state.params.villageId = result.values[0];
    state.params.villageName = state.communityList.find((village) => village.value === result.values[0])?.text;

    state.selectedBuildIds = [];
    state.cascader = [];
    state.cascaderData = [];
    ['buildHouseNumberNames', 'buildId', 'unitId', 'floorId', 'houseNumberId', 'houseNumber', 'buildName', 'unitName', 'floorName'].forEach((item) => {
      delete state.params[item];
    });
    if (result.values[0]) fetchBuildingTree(Number(result.values[0]));
    state.pickerCommunityShow = false;
  };

  /**
   * 联动选择器选择
   * @param val
   * @param ids
   */
  const handleCascadingChange = (val: TreeNode[], ids: number[]) => {
    state.cascader = val;
    state.selectedBuildIds = ids;
    ['buildHouseNumberNames', 'buildId', 'unitId', 'floorId', 'houseNumberId', 'buildName', 'unitName', 'floorName', 'houseNumber'].forEach((item) => {
      delete state.params[item];
    });
    state.params.buildHouseNumberNames = '';
    state.cascader.forEach((item, index) => {
      state.params.buildHouseNumberNames += index === 0 ? `${item.name}` : ` ${item.name}`;
      if (item.levels === 1) state.params = { ...state.params, buildId: item.id, buildName: item.name };
      if (item.levels === 2) state.params = { ...state.params, unitId: item.id, unitName: item.name };
      if (item.levels === 3) state.params = { ...state.params, floorId: item.id, floorName: item.name };
      if (item.levels === 4) state.params = { ...state.params, houseNumberId: item.id, houseNumber: item.name };
    });
    state.pickerBuildShow = false;
  };

  /**
   * 呼叫器保存地址
   */
  const handleCallerSavesAddress = () => {
    const { params } = state;
    if (!params.latitude || !params.longitude) {
      toast.show({ description: '请选择地址' });
      return;
    }
    if (!params.villageId) {
      toast.show({ description: '请选择小区' });
      return;
    }
    if (!params.buildHouseNumberNames) {
      toast.show({ description: '请选择详细地址' });
      return;
    }
    if (!params.linkName) {
      toast.show({ description: '请输入联系人' });
      return;
    }
    if (!params.phone) {
      toast.show({ description: '请输入联系号码' });
      return;
    }

    // 如果从订单界面来
    if (route.params!.variantIds) {
      state.params.variantIds = route.params!.variantIds;
      state.params.keepUp = 0;
    }
    Loading.show('保存中...');
    UserRequest.EditShippingAddress(params)
      .then((res) => {
        Loading.hide();
        if (res.data === 0) {
          ShowConfirmDialog({ title: '提示', message: '您的地址超出商家配送范围了', confirmText: '仍然保存', cancelText: '调整地址' }).then(() => {
            state.params.keepUp = 1;
            UserRequest.EditShippingAddress(params).then((res) => {
              toast.show({ description: '保存成功', duration: 1000 });
            });
          });
        } else {
          toast.show({ description: '保存成功', duration: 1000 });
          // 从提交订单页面来的那么就需要返回数据回去
          if (route.params?.variantIds) {
          } else {
            setTimeout(() => {
              navigation.navigate('receivingAddress', { refresh: true });
            }, 500);
          }
        }
      })
      .catch(() => Loading.hide());
  };

  const renderNoBeeperIdElement = () => (
    <React.Fragment>
      {selectPoint && (
        <View style={styles.selectAddress}>
          <View style={{ width: '70%' }}>
            <Text fontWeight={'bold'}>{selectPoint.address.address}</Text>
            <Text fontSize={12}>
              {selectPoint.address.province}
              {selectPoint.address.city}
              {selectPoint.address.district}
              {selectPoint.address.streetName}
            </Text>
          </View>
          <Button size="sm" padding={2} variant="outline" _text={{ color: CommonStyle.mainColor }} borderColor={CommonStyle.mainColor} onPress={() => navigation.navigate('selectMapPoint')}>
            修改地址
          </Button>
        </View>
      )}
      <View style={[styles.box, { marginTop: selectPoint ? 10 : '20%' }]}>
        {!selectPoint && (
          <Button size="sm" variant="outline" _text={{ color: CommonStyle.mainColor }} borderColor={CommonStyle.mainColor} onPress={() => navigation.navigate('selectMapPoint')}>
            选择收货地址
          </Button>
        )}
        <Field placeholder={'详细地址，例1层101室'} label={'门牌号'} value={formModel.houseNumber} onChangeText={(text) => (formModel.houseNumber = text)} />
        <Field placeholder={'请输入收货人姓名'} label={'联系人'} value={formModel.linkName} onChangeText={(text) => (formModel.linkName = text)} />
        <Field placeholder={'请输入收货手机号'} label={'联系号码'} value={formModel.phone} inputNumber onChangeText={(text) => (formModel.phone = text)} />
        <Button
          onPress={handleNoBeeperIdSaveAddress}
          bg={CommonStyle.mainColor}
          _pressed={{
            bg: CommonStyle.btnSelectMainColor,
          }}
          marginTop={'8'}
        >
          保存地址
        </Button>
        {route.params && route.params.id && (
          <Button
            onPress={handleDeleteAddress}
            _text={{ color: '#333' }}
            bg={'#F3F3F3'}
            _pressed={{
              bg: '#F0F0F0',
            }}
            marginTop={'4'}
          >
            删除地址
          </Button>
        )}
      </View>
    </React.Fragment>
  );

  const renderBeeperIdElement = () => (
    <React.Fragment>
      {selectPoint && (
        <View style={styles.selectAddress}>
          <View style={{ width: '70%' }}>
            <Text fontWeight={'bold'}>{selectPoint.address.address}</Text>
            <Text fontSize={12}>
              {selectPoint.address.province}
              {selectPoint.address.city}
              {selectPoint.address.district}
              {selectPoint.address.streetName}
            </Text>
          </View>
          <Button size="sm" padding={2} variant="outline" _text={{ color: CommonStyle.mainColor }} borderColor={CommonStyle.mainColor} onPress={() => navigation.navigate('selectMapPoint', { backScreen: 'bindAddress' })}>
            {selectPoint.address.address ? '修改地址' : '完善地址'}
          </Button>
        </View>
      )}
      <View style={[styles.box, { marginTop: selectPoint ? 10 : '20%' }]}>
        {!selectPoint && (
          <Button size="sm" variant="outline" _text={{ color: CommonStyle.mainColor }} borderColor={CommonStyle.mainColor} onPress={() => navigation.navigate('selectMapPoint', { backScreen: 'bindAddress' })}>
            选择收货地址
          </Button>
        )}
        <Field placeholder={'请选择小区'} editable={false} label={'小区'} value={state.params.villageName} onPress={() => (state.pickerCommunityShow = true)} />
        <Field placeholder={'请选择详细地址'} editable={false} label={'详细地址'} value={state.params.buildHouseNumberNames} onPress={() => (state.pickerBuildShow = true)} />
        <Field placeholder={'请输入联系人'} label={'联系人'} value={state.params.linkName} onChangeText={(text) => (state.params.linkName = text)} />
        <Field placeholder={'请输入联系人手机号'} label={'联系号码'} value={state.params.phone} inputNumber onChangeText={(text) => (state.params.phone = text)} />
        <Button bg={CommonStyle.mainColor} _pressed={{ bg: CommonStyle.btnSelectMainColor }} marginTop={'8'} onPress={handleCallerSavesAddress}>
          保存地址
        </Button>
      </View>

      <Picker visible={state.pickerCommunityShow} data={[state.communityList]} onConfirm={handlePickerConfirm} onCancel={() => (state.pickerCommunityShow = false)} title="选择小区" onChange={() => (state.pickerCommunityShow = false)} />
      <CascadingPicker show={state.pickerBuildShow} data={state.cascaderData} selectedIds={state.selectedBuildIds} onClose={() => (state.pickerBuildShow = false)} onConfirm={handleCascadingChange} title={'选择楼栋层门牌号'} />
    </React.Fragment>
  );

  return (
    <>
      <SafeAreaView style={styles.root}>{position ? <WebView source={{ uri: `https://kics.kanglailab.com/baiduMap?lng=${position?.lng}&lat=${position?.lat}` }} style={styles.web} /> : <WebView source={{ uri: `https://kics.kanglailab.com/baiduMap` }} style={styles.web} />}</SafeAreaView>
      <View style={styles.centent}>
        {active === 1 && renderNoBeeperIdElement()}
        {active === 2 && renderBeeperIdElement()}
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  root: { flex: 1 },
  web: { position: 'absolute', width: '100%', height: '100%' },
  centent: { width: '100%', height: '100%', alignItems: 'center', margin: 'auto', position: 'absolute' },
  box: { width: '95%', backgroundColor: 'white', marginTop: '20%', paddingHorizontal: 16, paddingVertical: 16, paddingBottom: 40, borderRadius: 8 },
  selectAddress: {
    width: '95%',
    backgroundColor: 'white',
    marginTop: '10%',
    paddingHorizontal: 16,
    paddingVertical: 16,
    borderRadius: 8,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
});

export default BindAddress;
